# 检测模拟车牌的轮廓
import math

import cv2

img = cv2.imread("./img/b.png")
# 获取img的宽高
img_h,img_w, d= img.shape
# 灰度化 --> 模糊 --> 二值化 --> 轮廓检测
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# 模糊（平滑） ：降噪
# blur_img = gray_img.copy()
# cv2.blur(gray_img,(3,3),blur_img)
# 二值化
ret,binary_img = cv2.threshold(gray_img,127,255,cv2.THRESH_BINARY)

# 轮廓检测
contours,h = cv2.findContours(binary_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

# cv2.drawContours(img,contours,-1,color=(0,0,255),thickness=2)

# 筛选所有的轮廓
for contour in contours:
    x,y,w,h = cv2.boundingRect(contour)
    # 过滤到大小的轮廓
    if w > img_w - 20 and h > img_h - 20 or w < 50 and h < 50:
        continue
    # cv2.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)

    # 计算封闭区间的周长
    peri = cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, float(0.04) * peri, True)

    print(approx) # 右上、右下、左下、左上
    # for item in approx:
    #     cv2.circle(img,item[0],6,color=(0,0,0),thickness=cv2.FILLED)
    [x1,y1] = approx[0][0] # 右上
    [x2,y2] = approx[3][0] # 左上

    # 反正切求角度
    theta = int(math.atan((y2 - y1) / (x2 - x1)) * 180 / math.pi)

    print(theta)
    # 矫正车牌
    M = cv2.getRotationMatrix2D((w // 2, h // 2),theta,1)
    # 旋转整个区域
    img = cv2.warpAffine(img,M,img.shape[:2])
cv2.imshow("img",img)
cv2.waitKey(0)